import 'dart:io';
import 'dart:typed_data';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';

class OcrService {
  final TextRecognizer _textRecognizer = TextRecognizer(
    script: TextRecognitionScript.chinese,
  );

  Future<String> recognizeText(String imagePath) async {
    try {
      final inputImage = InputImage.fromFilePath(imagePath);
      final recognizedText = await _textRecognizer.processImage(inputImage);

      return recognizedText.text.isEmpty ? '未识别到文字内容' : recognizedText.text;
    } catch (e) {
      return '识别失败，请重试';
    }
  }

  Future<String> recognizeTextFromBytes(Uint8List imageBytes) async {
    try {
      // 保存为临时文件然后识别
      final tempDir = await Directory.systemTemp.createTemp('ocr_');
      final tempFile = File('${tempDir.path}/temp_image.png');
      await tempFile.writeAsBytes(imageBytes);
      
      final result = await recognizeText(tempFile.path);
      
      // 清理临时文件
      await tempFile.delete();
      await tempDir.delete();
      
      return result;
    } catch (e) {
      return '识别失败，请重试';
    }
  }

  void dispose() {
    _textRecognizer.close();
  }
}
